package cn.edu.jxau.test;

import cn.edu.jxau.util.LinkedStack;
import cn.edu.jxau.util.Stack;

/**
 * Dijkstra双栈，仅能解决非常严格的四则运算，需要用左括号、右括号指定运算顺序，相当鸡肋
 * @author 付大石
 */
public class Main {
    
    public static void main(String[] args) {
        
//        String[] exp = {"(","1","+","(","(","2","+","3",")","*","(","4","*","5",")",")",")"};
//        String[] exp = {"(","(","1","+","sqrt","(","5.0",")",")","/","2.0",")"};
        String[] exp = {"1","+","2","*","3"};
        for(int i=0;i<exp.length;i++) {
            System.out.print(exp[i]);
        }
        System.out.println("\n");
        Stack<Double> valueStack = new LinkedStack<>();
        Stack<String> operationStack = new LinkedStack<>();
        for(String item : exp) {
            
            if(item.equals("(")) {
                //nothing to do
            } else if(item.equals("+")) {
                operationStack.push(item);
            } else if(item.equals("-")) {
                operationStack.push(item);
            } else if(item.equals("*")) {
                operationStack.push(item);
            } else if(item.equals("/")) {
                operationStack.push(item);
            } else if(item.equals("sqrt")) {
                operationStack.push(item);
            } else if(item.equals(")")) {
                String operation = operationStack.pop();
                double result = 0;
                double v = valueStack.pop();
                if(operation.equals("+")) {
                    result = valueStack.pop() + v;
                } else if(operation.equals("-")) {
                    result = valueStack.pop() - v;
                } else if(operation.equals("*")) {
                    result = valueStack.pop() * v;
                } else if(operation.equals("/")) {
                    result = valueStack.pop() / v;
                } else if(operation.equals("sqrt")) {
                    result = Math.sqrt(v);
                }
                valueStack.push(result);
            } else { //值
                valueStack.push(Double.parseDouble(item));
            }
        }
        double result = valueStack.pop();
        if(valueStack.isEmpty() && operationStack.isEmpty()) {
            System.out.println(result);
        } else {
            throw new RuntimeException("运算失败,可能是括号不匹配或者是有不支持的运算符");
        }
    }
}
